import type { App } from "vue"

/**
 * 保存一个对象到本地存储
 * @param key key
 * @param data 数据
 */
const save = (key: any, data: any) => {
  console.log('save json', key, data);
  
  localStorage.setItem(key, JSON.stringify(data))
}

/**
 * 在指定key的数据后面追加
 * @param key key
 * @param content 
 */
const append = (key: any, content: any) => {
  let data = getObj(key)
  data.push(content)
  save(key, data)
}

/**
 * 获取本地数据
 * @param key 
 * @returns 
 */
const get = (key: any): string | null => {
  return localStorage.getItem(key)
}

/**
 * 获取本地数据
 * @param key 
 * @returns Array Object
 */
const getObj = (key: any): any[] => {
  return JSON.parse(get(key) || '[]')
}

const getMessageByUser = (user: any) => {

}

class ChatMessageHolder {
  userId: any
  private _get: (key: any) => any[]
  private _append: (key: any, content: any) => void
  private _save: (key: any, data: any) => void
  data: any
  private KEY_PREFIX = 'chat_message'
  constructor(userId: any) {
    this._get = getObj.bind(this)
    this._append = append.bind(this)
    this._save = save.bind(this)
    this.data = {}
    this.userId = userId
  }

  /**
   * 加载某一个好友的聊天记录到内存
   * @param userId 好友Id
   */
  loadMessageByUser(userId: any): Array<any> {
    const key = `${this.KEY_PREFIX}_${this.userId}_${userId}`
    this.data[userId] = {
      update: false,
      data: getObj(key)
    }
    console.log(this.data[userId]);
    
    return this.data[userId].data
  }

  add(userId: any, message: any) {
    console.log(userId, message);
    // 判断是否有userId的聊天记录
    if (!this.data[userId]) {
      this.data[userId] = {
        update: true,
        data: [message]
      }
      this.save()
      return
    }

    // 存在， 添加新的消息记录
    // console.log(this.data[userId]);
    
    this.data[userId].data.push(message)
    this.data[userId].update = true
    this.save()
    
  }

  save() {

    console.log('save');
    
    Object.entries(this.data)
          .filter(([key, value]: any) => value.update == true)
          .forEach(([key, value]: any) => {
            const saveKey = `${this.KEY_PREFIX}_${this.userId}_${key}`
            this._save(saveKey, value.data)
          })
  }
}

export default ChatMessageHolder